package com.ocom.webapi.config;

import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.security.authentication.YoCiUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;

import java.util.Collection;
import java.util.Set;

/**
 * @Description: 德生需求
 * 主要是采用SpEL表达式语法，
 * @pms：是一个我们自己配置的spring容器起的别名，能够正确的找到这个容器类；
 * @Author: 朱晖
 * @Date: 2023/7/7
 **/
@Component("pms")
public class PermissionService {

	/**
	 * 判断接口是否有xxx:xxx权限
	 *
	 * @param permission 权限
	 * @return {boolean}
	 */
	public boolean hasPermission(String permission) {
		if (CommonUtil.isNull(permission)) {
			return false;
		}
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return false;
		}
		YoCiUser yoCiUser = (YoCiUser) authentication.getPrincipal();
		Set<String> Permissions = yoCiUser.getPermissions();

		return Permissions.contains(permission);
	}

	@Value("${platformSecret}")
	private String platformSecret;

	/**
	 * 判断接口是否有xxx:xxx权限
	 *
	 * @param permission 权限
	 * @return {boolean}
	 */
	public boolean hasRole(String permission) {
		if (CommonUtil.isNull(permission)) {
			return false;
		}
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return false;
		}
		YoCiUser yoCiUser = (YoCiUser) authentication.getPrincipal();


		Set<String> Permissions = yoCiUser.getPermissions();
		//因为多地部署  默认增加一个验证token来源
		String fromPlatform = "user:form:"+platformSecret;
		if (!Permissions.contains(fromPlatform)) {
			return false;
		}

		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
				.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
	}

}
